package com.whmnx.main.ui.model;

import android.app.Application;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.whmnx.base.bean.BaseBean;
import com.whmnx.base.bean.ImgResultBean;
import com.whmnx.base.bean.ProductBean;
import com.whmnx.base.bean.TreeBean;
import com.whmnx.base.constants.Constants;
import com.whmnx.base.constants.EventConstants;
import com.whmnx.base.http.CallBack;
import com.whmnx.base.http.HttpClient;
import com.whmnx.base.utils.FileUtil;
import com.whmnx.base.utils.ImageUtil;
import com.whmnx.base.utils.ImgVideoPickerUtils;
import com.whmnx.base.view.CommonDialog;
import com.whmnx.base.view.CustomPopWindow;
import com.whmnx.main.BR;
import com.whmnx.main.R;
import com.whmnx.main.databinding.FragmentAddCommodityBinding;
import com.whmnx.main.ui.adapter.PingDanAdapter;
import com.whmnx.main.ui.fragment.AddCommodityFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * author : huang
 * date   : 2020/9/27 0027 16:57
 * version: 1.0
 * @author Administrator
 */
public class CommodityModel extends ToolbarViewMainModel {

    private CustomPopWindow mPopupWindow;
    private AddCommodityFragment mFragment;
    private FragmentAddCommodityBinding mBinding;
    private android.widget.ListView listView;
    private int pwHeight = 800;
    private List<String> list = new ArrayList<>();

    private String photosUrl = "";
    private String keyId = "";
    private List<TreeBean> resultList;


    //商品名称
    public ObservableField<String> ProductCategory_Name  = new ObservableField<>("");

    public ObservableField<String> Product_SPEC  = new ObservableField<>("");

    public ObservableField<String> Product_Price  = new ObservableField<>("");

    public ObservableField<String> Product_Range  = new ObservableField<>();

    public ObservableField<String> Product_Remark  = new ObservableField<>("");
    //商品分类
    public ObservableField<String> ProductCategory_Id  = new ObservableField<>("");

    private ArrayList<String> list_path = new ArrayList<>();

    private List<String> data;

    PingDanAdapter  pingDanAdapter;

    //给RecyclerView添加ObservableList
    public ObservableList observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<AddComItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_add_com);
    //


    public List<ProductBean.SpecModelBean> specModelBeans = new ArrayList<>();
    private String productVideo = "";


    public CommodityModel(@NonNull Application application) {
        super(application);
    }

    public void initToolbar(AddCommodityFragment addCommodityFragment, FragmentAddCommodityBinding binding) {
        this.mFragment = addCommodityFragment;
        this.mBinding = binding;
        setTitleText("添加商品");
        getTree();
        initList();
        initData();
    }

    private void initData() {
        if (mFragment.entity != null){
            ProductCategory_Name.set(mFragment.entity.Product_Name);
           // Product_SPEC.set(mFragment.entity.Product_SPEC);
         //   Product_Price.set(mFragment.entity.Product_Price);

            ProductCategory_Id.set(mFragment.entity.ProductCategory_Name);
            Product_Range.set(mFragment.entity.Product_Range);
            Product_Remark.set(mFragment.entity.Product_Remark);
            keyId = mFragment.entity.ProductCategory_Id;
            if (mFragment.entity.Product_Status == 0){
                mBinding.cb1.setChecked(true);
            }else {
                mBinding.cb2.setChecked(true);
            }

            //添加商品
            productVideo = mFragment.entity.Product_Video;
            ImageUtil.setImage(mBinding.ivVedio,productVideo);

            if (!TextUtils.isEmpty(mFragment.entity.Product_Image)){
                String[] split = mFragment.entity.Product_Image.split(",");
                ArrayList<String> photos = new ArrayList<>();
                for (String s : split) {
                    photos.add(s.contains(Constants.HOST) ? s : Constants.HOST + s);
                }
                mBinding.snplMomentAddPhotos.setData(photos);
            }

            if (mFragment.entity.SPECModel.size() > 0){
                for (ProductBean.SpecModelBean specModelBean : mFragment.entity.SPECModel) {
                    specModelBeans.add(specModelBean);
                    observableList.add(new AddComItemViewModel(CommodityModel.this, specModelBean));
                }
            }

            if (mFragment.entity.Product_Type == 1){
                mBinding.cbKnot.setChecked(true);
                mBinding.llPin.setVisibility(View.VISIBLE);
                pingDanAdapter.addAll(specModelBeans);
            }
        }


        mBinding.cbKnot.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                mBinding.llPin.setVisibility(View.VISIBLE);
                if (specModelBeans.size() > 0){
                    pingDanAdapter.replaceAll(specModelBeans,true);
                }else {
                    ToastUtils.showShort("请先添加拼团价格");
                }
            }else {
                mBinding.llPin.setVisibility(View.GONE);
            }
        });
    }

    private void initList() {
        listView = new android.widget.ListView(mFragment);
        //隐藏滚动条
        listView.setVerticalScrollBarEnabled(false);
        ArrayAdapter<String> adapter = new ArrayAdapter(mFragment, R.layout.item_array,list);
        listView.setAdapter(adapter);
        listView.setBackground(ContextCompat.getDrawable(mFragment, R.drawable.gray_drawable_bg2));
        //设置listview的点击事件
        listView.setOnItemClickListener((parent, view, position, id) -> {
            mBinding.tvTree.setText(list.get(position));
             keyId = resultList.get(position).getKey();
             mPopupWindow.dissmiss();
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(mFragment);
        //配置布局，默认为vertical（垂直布局），下边这句将布局改为水平布局
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mBinding.rvList.setLayoutManager(layoutManager);
        mBinding.rvList.setItemAnimator(new DefaultItemAnimator());
          pingDanAdapter = new PingDanAdapter(mFragment,CommodityModel.this);
        mBinding.rvList.setAdapter(pingDanAdapter);
    }

    private void getTree() {
        Map<String, Object> params = new HashMap<>();
        params.put("uId", SPUtils.getInstance().getString(Constants.USERID));
        HttpClient.get(mFragment, Constants.GETCATEGORYTREE, params,new CallBack<List<TreeBean>>() {
            @Override
            public void onSuccess(List<TreeBean> result) {
                Constants.TREEBEANS = result;
                list.clear();
                resultList = result;
                for (TreeBean treeBean : result) {
                    list.add(treeBean.getTitle());
                }
            }
        });
    }


    //商品规格
    public BindingCommand specOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            String s2 = "添加商品规格";
            new CommonDialog(mFragment, R.style.dialog, s2,2, (dialog, confirm, input,s) -> {
                if (confirm) {
                    //商品规格
                 //   Product_SPEC.set(input);
                    //价格
                 //   Product_Price.set(s);
                    ProductBean.SpecModelBean specModelBean =  new ProductBean.SpecModelBean();
                    specModelBean.setProductSPEC_Name(input);
                    specModelBean.setProductSPEC_Price(s);
                    specModelBeans.add(specModelBean);
                    pingDanAdapter.replaceAll(specModelBeans,true);
                    observableList.add(new AddComItemViewModel(CommodityModel.this, specModelBean));
                }
                dialog.dismiss();
            }).show();
        }
    });


    //添加视频
    public BindingCommand vedioOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            ImgVideoPickerUtils.openVideo(mFragment);
        }
    });

    /**
     * 删除条目
     *
     * @param
     * @param specModelBean
     */
    public void deleteItem(AddComItemViewModel addComItemViewModel, ProductBean.SpecModelBean specModelBean) {
        //点击确定，在 observableList 绑定中删除，界面立即刷新
        observableList.remove(addComItemViewModel);
        specModelBeans.remove(specModelBean);
        pingDanAdapter.replaceAll(specModelBeans,true);
       // RxBus.getDefault().post(EventConstants.ADD2);
    }


    //商品分类
    public BindingCommand OnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            mPopupWindow = new CustomPopWindow.PopupWindowBuilder(mFragment)
                    .setView(listView)
                    .size(mBinding.tvTree.getWidth(), listView.getHeight())
                    .setFocusable(true)
                    .setOutsideTouchable(true)
                    .enableBackgroundDark(false)
                    //    .setBackgroundDrawable(ContextCompat.getDrawable(mActivity.getActivity(), R.drawable.white_drawable_oval))
                    .setBgDarkAlpha((float) 1)
                    .create();
            mPopupWindow.showAsDropDown(mBinding.tvTree, 0, 15);
        }
    });

    private String shortPath = "";
    //添加商品
    public BindingCommand OnClickCommand2 = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (mBinding.snplMomentAddPhotos.getData().size() == 0){
                ToastUtils.showShort("请添加商品图片");
                return;
            }
            if (TextUtils.isEmpty(ProductCategory_Id.get())){
                ToastUtils.showShort("请添加商品分类");
                return;
            }
            if (TextUtils.isEmpty(ProductCategory_Name.get())){
                ToastUtils.showShort("请添加商品名称");
                return;
            }
            if (specModelBeans.size() == 0){
                ToastUtils.showShort("请添加商品规格");
                return;
            }

            if (TextUtils.isEmpty(Product_Range.get() + "")){
                ToastUtils.showShort("请添加限售范围");
                return;
            }
            if (TextUtils.isEmpty(Product_Remark.get())){
                ToastUtils.showShort("请添加辅助说明");
                return;
            }

            if (mBinding.cbKnot.isChecked()){
                for (ProductBean.SpecModelBean specModelBean : specModelBeans) {
                    if(TextUtils.isEmpty(specModelBean.getProductSPEC_GroupPrice())){
                        ToastUtils.showShort("请添加拼团价格");
                        return;
                    }
                }
            }

           if (!mBinding.cb1.isChecked() && !mBinding.cb2.isChecked()){
               ToastUtils.showShort("请选择商品状态");
               return;
           }
            data = mBinding.snplMomentAddPhotos.getData();

            if (!TextUtils.isEmpty(mFragment.videoPath)){
                List<File> files = new ArrayList<>();
                File file = new File(mFragment.videoPath);
                files.add(file);
                HttpClient.postImg(mFragment, Constants.UPLOADHEADIMG, files, new CallBack<List<ImgResultBean>>() {
                    @Override
                    public void onSuccess(List<ImgResultBean> baseBean) {
                        for (ImgResultBean imgResultBean : baseBean) {
                            shortPath = imgResultBean.shortPath;
                        }
                        updateImg();
                    }
                });
            }else {
                updateImg();
            }
        }
    });

    private void updateImg() {
        list_path.clear();
        for (String datum : mBinding.snplMomentAddPhotos.getData()) {
            if (datum.contains("http")) {
                list_path.add(datum);
                if (data.size() == list_path.size()) getUpdate();
            } else {
                List<File> files = new ArrayList<>();
                File file = new File(FileUtil.compressImage(datum));
                files.add(file);
                HttpClient.postImg(mFragment, Constants.UPLOADHEADIMG, files, new CallBack<List<ImgResultBean>>() {
                    @Override
                    public void onSuccess(List<ImgResultBean> baseBean) {
                        for (ImgResultBean imgResultBean : baseBean) {
                            list_path.add(imgResultBean.shortPath);
                            if (data.size() == list_path.size()) getUpdate();
                            break;
                        }
                    }
                });
            }
        }
    }

    //添加商品
    private void getUpdate() {
        Map<String, Object> params = new HashMap<>();
        ProductBean productBean  =   new ProductBean();

        if (mFragment.entity != null){
            productBean.setProduct_Id(mFragment.entity.Product_Id);
        }
        ProductBean.PathModelBean pathModelBean = new ProductBean.PathModelBean();
        List<ProductBean.PathModelBean> list = new ArrayList<>();

        for (String s : list_path) {
            String s1;
            if (s.contains("http")){
                s1 = s.split(Constants.HOST)[1];
            }else {
                s1 = s;
            }
            photosUrl += s1 + ",";
        }

        pathModelBean.setPath_Url(photosUrl.substring(0, photosUrl.length()-1));
        list.add(pathModelBean);
        productBean.setPathModel(list);

        if (mFragment.videoPath != null){
            productBean.setProduct_Video(shortPath);
        }else {
            productBean.setProduct_Video(productVideo);
        }


        productBean.setProductCategory_Id(keyId);
        productBean.setProduct_Name(ProductCategory_Name.get());

        /*ProductBean.SpecModelBean specModelBean =  new ProductBean.SpecModelBean();
        specModelBean.setProductSPEC_Name(Product_SPEC.get());
        specModelBean.setProductSPEC_Price(Product_Price.get());
        List<ProductBean.SpecModelBean> list2 = new ArrayList<>();
        list2.add(specModelBean);*/
        productBean.setSpecModel(specModelBeans);

        productBean.setProduct_Range(Integer.parseInt(Product_Range.get()));
        productBean.setProduct_Remark(Product_Remark.get());
        if (mBinding.cbKnot.isChecked()){
            //拼单
            productBean.setProduct_Type(1);
        }else {
            productBean.setProduct_Type(0);
        }

        if (mBinding.cb1.isChecked()){
            productBean.setProduct_Status(0);
        }else {
            productBean.setProduct_Status(1);
        }
        params.put("",productBean);
        HttpClient.post(mFragment, Constants.ADDORUPDATE, params,new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean result) {
                if (mFragment.entity != null){
                    ToastUtils.showShort("编辑商品成功");
                }else {
                    ToastUtils.showShort("添加商品成功");
                }
                RxBus.getDefault().post(EventConstants.ADD);
                finish();
            }
        });

    }
}
